import React, { useEffect, useState } from 'react';
import { Button, Descriptions, Radio, Spin, message, Tag, Typography } from 'antd';
import type { DescriptionsProps, RadioChangeEvent } from 'antd';
import type { IGanyut } from '~/types/ganyut';
import http from '~/api/http';
import dayjs from 'dayjs';
import { CheckOutlined, CloseOutlined, FileDoneOutlined } from '@ant-design/icons';

const { Text } = Typography;


// 所有体质字段映射（字段名→显示标签）
const constitutionFields: Record<string, string> = {
  qi: '气虚质',
  yan: '痰湿质',
  yin: '阴虚质',
  te: '特禀质',
  yang: '阳虚质',
  xue: '血瘀质',
  shi: '湿热质',
  yu: '气郁质',
  pin:'平和质'
};

interface AddFormProps1 {
  onSuccess?: () => void;
  onCancel?: () => void;
  value: number;
}

const App: React.FC<AddFormProps1> = ({ onSuccess, onCancel, value }) => {
  const [size, setSize] = useState<'default' | 'middle' | 'small'>('default');
  const [ganyut1, setGanyut1] = useState<IGanyut>({
    id: 0,
    pdata: new Date(),
    qi: 0,
    yan: 0,
    yin: 0,
    te: 0,
    yang: 0,
    xue: 0,
    shi: 0,
    yu: 0,
    pin: 0,
    bid: 0,
    name: '',
    age: 0,
    sex: '',
    fileNumber: ''
  });
  const [loading, setLoading] = useState(true);

  // 核心：按“是/否”分类体质字段
  const getClassifiedConstitutions = () => {
    const yesList: string[] = []; // 存“是”的体质
    const noList: string[] = [];  // 存“否”的体质

    // 遍历所有体质字段，按值分类
    Object.entries(constitutionFields).forEach(([field, label]) => {
      const value = ganyut1[field as keyof IGanyut];
      if (value === 1) {
        yesList.push(label);
      } else {
        noList.push(label);
      }
    });

    return { yesList, noList };
  };

  // 生成描述项（包含分类后的体质展示）
  const getBorderedItems = (): DescriptionsProps['items'] => {
    const { yesList, noList } = getClassifiedConstitutions();

    return [
      // 1. 基础信息
      { key: '1', label: '体测编号', children: ganyut1.id },
      { key: '2', label: '姓名', children: ganyut1.name || '-' },
      { key: '3', label: '年龄', children: ganyut1.age || '-' },
      { key: '4', label: '性别', children: ganyut1.sex || '-' },
      { 
        key: '5', 
        label: '评估日期', 
        children: ganyut1.pdata ? dayjs(ganyut1.pdata).format('YYYY-MM-DD') : '-' 
      },

      // 2. “是”的体质（分组展示）
      {
        key: '6',
        label: (
          <Text strong style={{ color: '#c41a4dff' }}>
            符合体质 <CheckOutlined />
          </Text>
        ),
        children: yesList.length > 0 ? (
          yesList.map((label, idx) => (
            <Tag key={idx} icon={<CheckOutlined />} color="error" style={{ margin: '0 4px 4px 0' }}>
              {label}
            </Tag>
          ))
        ) : (
          <Text type="secondary">无</Text>
        ),
      },

      // 3. “否”的体质（分组展示）
      {
        key: '7',
        label: (
          <Text strong style={{ color: '#4dffa6ff' }}>
            不符体质 <FileDoneOutlined />
          </Text>
        ),
        children: noList.length > 0 ? (
          noList.map((label, idx) => (
            <Tag key={idx} icon={<FileDoneOutlined />} color="success" style={{ margin: '0 4px 4px 0' }}>
              {label}
            </Tag>
          ))
        ) : (
          <Text type="secondary">无</Text>
        ),
      },

      // 4. 其他固定信息
      
    ];
  };

  const onChange = (e: RadioChangeEvent) => {
    setSize(e.target.value);
  };

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const response = await http.getList<IGanyut>('Ganyut/chay', {});
      const matchedItem = response.data.find(item => item.id === value);
      
      if (matchedItem) {
        setGanyut1(matchedItem);
      } else {
        message.warning('未找到对应的体测记录');
      }
    } catch (error) {
      message.error('获取数据失败，请重试');
      console.error('请求错误:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchUsers();
  }, [value]);

  return (
    <div>
      <Spin spinning={loading}>
        <div style={{ marginBottom: 16, fontSize: 14, color: '#666' }}>
          当前查看的档案ID：
          <span style={{ color: '#1890ff', fontWeight: 500 }}>
            {ganyut1.fileNumber || '加载中...'}
          </span>
        </div>

        <Radio.Group onChange={onChange} value={size}>
          <Radio value="default">default</Radio>
          <Radio value="middle">middle</Radio>
          <Radio value="small">small</Radio>
        </Radio.Group>
        <br /><br />

        <Descriptions
          bordered
          title="体测详情"
          size={size}
          
          items={getBorderedItems()}
        />
        <br /><br />

     
      </Spin>
    </div>
  );
};

export default App;